<template>
  <Card>
    <Form :model="attr" :rules="rules" ref="form" @finish="submitForm">
      <FormItem label="属性名" name="attrName" :labelCol="{ span: 2 }" :wrapperCol="{ span: 4 }">
        <Input v-model:value="attr.attrName" placeholder="请输入属性名" />
      </FormItem>
      <Button type="primary" :disabled="!attr.attrName" @click="addEmptyAttrValue">
        <template #icon><PlusOutlined /></template>
        添加属性值
      </Button>
      <FormItem name="attrValueList">
        <Table
          :dataSource="attr.attrValueList"
          :columns="columns"
          :pagination="false"
          rowKey="id"
          bordered
          class="attr-table"
        >
          <template #index="{ index }">
            {{ index + 1 }}
          </template>
          <!-- 
            record 遍历行数据
            text 当前logoUrl数据
            index 下标
            record table列信息
          -->
          <template #attrValueList="{ record, index }">
            <Input
              v-if="record.isEdit"
              :ref="
                (el) => {
                  if (el) inputs[index] = el;
                }
              "
              v-model:value="record.valueName"
              placeholder="请输入属性值"
              @blur="addAttrValue(record, index)"
            />
            <div v-else @click="showEdit(record, index)">{{ record.valueName }}</div>
          </template>

          <template #operator="{ index }">
            <Popconfirm title="您确认要删除吗？" @confirm="delAttrValue(index)">
              <template #icon><QuestionCircleOutlined style="color: red" /></template>
              <Button type="primary" danger class="attr-list-btn"> 删除 </Button>
            </Popconfirm>
          </template>
        </Table>
      </FormItem>
      <FormItem>
        <Button type="primary" html-type="submit"> 确定 </Button>
        <Button class="attr-btn" @click="$emit('setIsShowAttrList', true)"> 取消 </Button>
      </FormItem>
    </Form>
  </Card>
</template>
<script lang="ts" setup>
  import { ref, reactive, nextTick, defineEmits, defineProps } from 'vue';
  import { Card, Form, FormItem, Input, Button, Table, Popconfirm, message } from 'ant-design-vue';
  import { RuleObject } from 'ant-design-vue/es/form/interface';
  import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue';
  import { saveOrUpdateAttrApi } from '/@/api/product/attr';
  import { useCategoryStore } from '/@/store/modules/category';
  import { AttrValueList, AttrValueItem, Attr } from '/@/api/product/model/attrModel';

  const emits = defineEmits(['setIsShowAttrList']);
  const props = defineProps(['currentAttr']);

  const categoryStore = useCategoryStore();

  // 表单数据
  const attr = reactive<Attr>(props.currentAttr);
  // 属性值验证规则
  // 不需要使用的参数前面加上“下划线”，ts就不会报错了
  const asyncValidator = (_rule: RuleObject, value: AttrValueList) => {
    return new Promise((resolve, reject) => {
      if (!value.length) {
        reject('请至少添加一个属性值');
        return;
      }
      resolve(null);
    });
  };
  // 表单验证规则
  const rules = {
    attrName: [{ required: true, message: '请输入属性名', trigger: 'blur' }],
    attrValueList: [{ required: true, asyncValidator }],
  };
  // 列
  const columns = [
    {
      // 表格列标题
      title: '序号',
      // 遍历元素key属性
      key: '1',
      // 宽度
      width: 70,
      // 居中
      align: 'center',
      slots: {
        // 插槽的名称
        customRender: 'index',
      },
    },
    {
      title: '属性值列表',
      dataIndex: 'attrValueList',
      key: '2',
      slots: {
        // 插槽的名称
        customRender: 'attrValueList',
      },
    },
    {
      title: '操作',
      key: '3',
      slots: {
        // 插槽的名称
        customRender: 'operator',
      },
      width: 200,
    },
  ];

  const inputs = ref<HTMLInputElement[]>([]);
  // 点击添加属性值按钮触发事件回调
  const addEmptyAttrValue = () => {
    attr.attrValueList.push({
      valueName: '',
      id: attr.attrValueList.length,
      isEdit: true,
    });

    nextTick(() => {
      inputs.value[attr.attrValueList.length - 1].focus();
    });
  };

  // input失去焦点
  const addAttrValue = (attrValue: AttrValueItem, index: number) => {
    if (!attrValue.valueName) {
      attr.attrValueList.splice(index, 1);
      return;
    }
    attrValue.isEdit = false;
  };

  const showEdit = (attrValue: AttrValueItem, index: number) => {
    attrValue.isEdit = true;
    nextTick(() => {
      inputs.value[index].focus();
    });
  };

  const delAttrValue = (index: number) => {
    attr.attrValueList.splice(index, 1);
  };

  const form = ref(null);

  const submitForm = async () => {
    const { attrName, attrValueList, id } = attr;

    await saveOrUpdateAttrApi({
      attrName,
      attrValueList: attrValueList.map((attrValue) => {
        return {
          valueName: attrValue.valueName,
        };
      }),
      categoryLevel: 3,
      categoryId: categoryStore.category3Id,
      id,
    });

    message.success(`${id ? '更新' : '添加'}属性成功`);
    // 触发自定义事件
    emits('setIsShowAttrList', true);
  };
</script>

<style scoped>
  .attr-table {
    margin-top: 20px;
  }

  .attr-btn {
    margin-left: 10px;
  }
</style>
